package me.zhengjie.modules.exam;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.AnonymousAccess;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api")
public class first {
    @AnonymousAccess
    @PostMapping("/processExcel")
    public String processExcel(@RequestParam("file") MultipartFile multipartFile,
                               @RequestParam("outputDirectory") String outputDirectory,
                               @RequestParam("minAnswerCount") int minAnswerCount,
                               @RequestParam("maxAnswerCount") int maxAnswerCount,
                               @RequestParam("minScore") int minScore,
                               @RequestParam("maxScore") int maxScore
    ) throws IOException {

        File inputFile = convertMultiPartFileToFile(multipartFile);

        try (Workbook workbook = WorkbookFactory.create(new FileInputStream(inputFile))) {
            Sheet sheet = workbook.getSheetAt(0); // 假设只有一个工作表
            int rowCount = sheet.getLastRowNum() - sheet.getFirstRowNum();

            Map<String, Integer> nameCountMap = new HashMap<>();
            Map<String, Integer> nameScoreMap = new HashMap<>();
            // 遍历每一行并统计学生姓名出现的次数
            for (int i = 1; i <= rowCount; i++) {
                Row row = sheet.getRow(i); // 获取当前行
                Cell firstCell = row.getCell(0); // 获取第一个单元格对象

                // 检查当前行的第一个单元格是否为空
                if (firstCell == null || firstCell.getCellType() == CellType.BLANK) {
                    break; // 如果为空，则停止遍历
                }

                Cell nameCell = row.getCell(1); // 获取第二列的单元格对象

                String names = nameCell.getStringCellValue();

                // 拆分学生姓名
                String[] nameArray = names.split("，");

                // 统计每个学生姓名出现的次数
                for (String name : nameArray) {
                    name = name.trim(); // 去除姓名前后的空格
                    nameCountMap.put(name, nameCountMap.getOrDefault(name, 0) + 1);

                    int questionCount = nameCountMap.get(name);
                    int score;

                    if (questionCount ==minScore) {
                        score = 1;
                    } else if (questionCount > (maxAnswerCount-1)) {
                        score = 20;
                    } else {
                        score = ((questionCount - minAnswerCount) * (maxScore - minScore)) / (maxAnswerCount - minAnswerCount) + minScore;
                    }

                    nameScoreMap.put(name, score);
                }
            }

            // 创建一个新的工作簿和工作表，并写入姓名及出现次数
            Workbook newWorkbook = new XSSFWorkbook();
            Sheet newSheet = newWorkbook.createSheet("姓名统计");

            int rowIdx = 0;

            // 写入表头
            Row headerRow = newSheet.createRow(rowIdx++);
            headerRow.createCell(0).setCellValue("姓名");
            headerRow.createCell(1).setCellValue("次数");
            headerRow.createCell(2).setCellValue("得分");

            // 写入姓名及出现次数
            for (Map.Entry<String, Integer> entry : nameCountMap.entrySet()) {
                String name = entry.getKey();
                int count = entry.getValue();
                int score = nameScoreMap.getOrDefault(name, 0);
                Row dataRow = newSheet.createRow(rowIdx++);
                dataRow.createCell(0).setCellValue(name);
                dataRow.createCell(1).setCellValue(count);
                dataRow.createCell(2).setCellValue(score);
            }

            // 创建输出目录
            File outputDir = new File(outputDirectory);
            if (!outputDir.exists()) {
                outputDir.mkdirs();
            }

            // 生成输出文件路径
            String outputFile = outputDirectory + "output.xlsx";

            // 将创建好的工作簿写入输出文件
            try (FileOutputStream outputStream = new FileOutputStream(outputFile)) {
                newWorkbook.write(outputStream);
            }

            // 删除临时输入文件
            inputFile.delete();

            return "输出文件创建成功！";
        } catch (IOException e) {
            e.printStackTrace();
            return "处理Excel文件时发生错误！";
        }
    }

    // 将 MultipartFile 转换为 File
    private File convertMultiPartFileToFile(MultipartFile multipartFile) throws IOException {
        File file = new File(multipartFile.getOriginalFilename());
        try (OutputStream os = new FileOutputStream(file)) {
            os.write(multipartFile.getBytes());
        }
        return file;
    }


}
